package com.ray.system.service.compose;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ray.common.SysMsgCodeConstant;
import com.ray.common.check.AbstractCheck;
import com.ray.system.builder.LoginBuilder;
import com.ray.system.builder.UserBuilder;
import com.ray.system.builder.UserCompanyBuilder;
import com.ray.system.builder.UserPositionBuilder;
import com.ray.system.check.PositionCheck;
import com.ray.system.check.UserCheck;
import com.ray.system.enums.MenuTypeEnum;
import com.ray.system.service.*;
import com.ray.system.table.dto.MenuQueryDTO;
import com.ray.system.table.entity.*;
import com.ray.system.table.params.company.AdminUserEditParams;
import com.ray.system.table.params.company.CompanyUserCreateParams;
import com.ray.system.table.params.company.CompanyUserEditParams;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.result.MsgCodeConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * @author bo shen
 * @Description: 用户聚合服务
 * @Class: UserService
 * @Package com.ray.system.service.compose
 * @date 2020/5/29 10:26
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Service
public class UserService {

    @Autowired
    private SysUserPositionService sysUserPositionService;
    @Autowired
    private SysPositionService sysPositionService;
    @Autowired
    private SysUserCompanyService sysUserCompanyService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 获取用户在当前公司的职位
     *
     * @param userCode
     * @return
     */
    public SysPosition queryPositionByLogin(String userCode, String companyCode) {
        ValidateUtil.hasLength(userCode, "参数[userCode]不能为空");
        ValidateUtil.hasLength(companyCode, "参数[companyCode]不能为空");
        //获取公司 职位
        SysUserPosition sysUserPosition = sysUserPositionService.queryPositionByLogin(userCode, companyCode);
        //存在职位就返回职位详情
        if (ObjectUtil.isNotNull(sysUserPosition)) {
            return sysPositionService.queryPositionByLogin(sysUserPosition.getPositionCode());
        }
        return null;
    }

    /**
     * 获取当前登录人对应系统菜单
     *
     * @param appCode
     * @param loginUser
     * @return
     */
    public List<SysMenu> leftMenu(String appCode, LoginUser loginUser) {
        ValidateUtil.hasLength(appCode, "参数[appCode]不能为空");
        List<SysMenu> list = null;
        //查询用户在系统下拥有的角色
        if (loginUser.isAllData()) {
            //拥有所有
            list = sysMenuService.queryMenuByAppCode(appCode, Arrays.asList(MenuTypeEnum.MENU.getValue()), loginUser);
        } else {
            list = sysMenuService.listByUserCode(loginUser.getUserCode(), appCode, Arrays.asList(MenuTypeEnum.MENU.getValue()));
        }
        return list;
    }

    /**
     * 获取当前登录人对应系统按钮
     *
     * @param appCode
     * @param loginUser
     * @return
     */
    public List<SysMenu> leftBtn(String appCode, LoginUser loginUser) {
        ValidateUtil.hasLength(appCode, "参数[appCode]不能为空");
        List<SysMenu> list = null;
        //查询用户在系统下拥有的角色
        if (loginUser.isAllData()) {
            //拥有所有
            list = sysMenuService.queryMenuByAppCode(appCode, Arrays.asList(MenuTypeEnum.BTN.getValue()), loginUser);
        } else {
            list = sysMenuService.listByUserCode(loginUser.getUserCode(), appCode, Arrays.asList(MenuTypeEnum.BTN.getValue()));
        }
        return list;
    }

    /**
     * 获取当前登录人对应系统功能
     *
     * @param appCode
     * @param loginUser
     * @return
     */
    public List<SysMenu> leftFun(String appCode, LoginUser loginUser) {
        ValidateUtil.hasLength(appCode, "参数[appCode]不能为空");
        List<SysMenu> list = null;
        //查询用户在系统下拥有的角色
        if (loginUser.isAllData()) {
            //拥有所有
            list = sysMenuService.queryMenuByAppCode(appCode, Arrays.asList(MenuTypeEnum.FUNCTION.getValue()), loginUser);
        } else {
            list = sysMenuService.listByUserCode(loginUser.getUserCode(), appCode, Arrays.asList(MenuTypeEnum.FUNCTION.getValue()));
        }
        return list;
    }

    /**
     * 给公司创建人员
     *
     * @param createParams
     * @param loginUser
     * @return
     */
    public boolean createUser(CompanyUserCreateParams createParams, LoginUser loginUser) {
        //判断职位是否存在
        SysPosition sysPosition = sysPositionService.queryGPositionByPositionCode(createParams.getPositionCode());
        new PositionCheck(sysPosition).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        //判断手机号码是否存在
        SysUser sysUser = sysUserService.queryUserByMobile(createParams.getMobile());
        String userCode;
        if (ObjectUtil.isNull(sysUser)) {
            UserBuilder userBuilder = new UserBuilder();
            userBuilder.append(createParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
            //保存用户信息
            if (!sysUserService.save(userBuilder.bulid())) {
                log.info("在公司下保存用户接口异常,参数:{}", JSON.toJSONString(userBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
            //保存登录信息
            LoginBuilder loginBuilder = new LoginBuilder();
            loginBuilder.appendCode(userBuilder.getCode()).appendLoginName(createParams.getMobile()).appendCreate(loginUser);
            if (!sysLoginService.save(loginBuilder.bulid())) {
                log.info("保存登录信息接口异常,参数:{}", JSON.toJSONString(userBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
            userCode = userBuilder.getCode();
        } else {
            //判断用户是否已经在公司下面
            userCode = sysUser.getUserCode();
        }
        SysUserCompany userCompany = sysUserCompanyService.queryLink(userCode, createParams.getCompanyCode());
        if (ObjectUtil.isNull(userCompany)) {
            //创建用户与公司的关联--直接获取公司
            UserCompanyBuilder userCompanyBuilder = new UserCompanyBuilder();
            userCompanyBuilder.appendCompanyCode(loginUser.getCompanyCode())
                    .appendDeptCode(createParams.getCompanyCode())
                    .appendUserCode(userCode).appendCreate(loginUser);
            if (!sysUserCompanyService.save(userCompanyBuilder.bulid())) {
                log.info("保存登录信息接口异常,参数:{}", JSON.toJSONString(userCompanyBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
        }
        //保存职位信息
        UserPositionBuilder userPositionBuilder = new UserPositionBuilder();
        userPositionBuilder.appendCode(userCode).appendCompanyCode(loginUser.getCompanyCode())
                .appendPositionCode(createParams.getPositionCode()).appendCreate(loginUser);
        if (!sysUserPositionService.save(userPositionBuilder.bulid())) {
            log.info("保存职位接口异常,参数:{}", JSON.toJSONString(userPositionBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return true;
    }

    /**
     * 查询当前用户拥有的菜单
     *
     * @param appCode
     * @param loginUser
     * @return
     */
    public List<SysMenu> queryMenus(String appCode, LoginUser loginUser) {
        if (loginUser.isAllData()) {
            //菜单权限
            MenuQueryDTO queryDTO = new MenuQueryDTO();
            queryDTO.setAppCode(appCode);
            return sysMenuService.list(queryDTO, loginUser);
        } else {
            //获取用户拥有的菜单
            return sysMenuService.listByUserCode(loginUser.getUserCode(), appCode, null);
        }
    }

    /**
     * 编辑用户
     * @param editParams
     * @param loginUser
     * @return
     */
    public Boolean editUser(CompanyUserEditParams editParams, LoginUser loginUser) {
        SysPosition extPosition = sysPositionService.queryGPositionByPositionCode(editParams.getPositionCode());
        new PositionCheck(extPosition).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        //判断手机号码是否存在
        SysUser sysUser = sysUserService.queryUserByUserCode(editParams.getUserCode(), loginUser);
        new UserCheck(sysUser).checkNull("用户不存在");
        SysUserCompany userCompany = sysUserCompanyService.queryLink(editParams.getUserCode(), editParams.getCompanyCode());
        new AbstractCheck<>(userCompany).checkNull("无权限修改该用户");
        //更新职位信息
        SysUserPosition sysPosition = sysUserPositionService.queryPositionByLogin(editParams.getUserCode(), editParams.getCompanyCode());
        if (ObjectUtil.isNull(sysPosition)) {
            //保存职位信息
            //职位不存在
            UserPositionBuilder userPositionBuilder = new UserPositionBuilder();
            userPositionBuilder.appendCode(editParams.getUserCode()).appendCompanyCode(loginUser.getCompanyCode())
                    .appendPositionCode(editParams.getPositionCode()).appendCreate(loginUser);
            //新增保存
            log.info("保存用户:{},职位：",sysUser.getUserName(),extPosition.getPositionName());
            if (!sysUserPositionService.save(userPositionBuilder.bulid())) {
                log.info("保存职位接口异常,参数:{}", JSON.toJSONString(userPositionBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
        } else{
            UserPositionBuilder userPositionBuilder = new UserPositionBuilder();
            userPositionBuilder.appendCode(editParams.getUserCode()).appendCompanyCode(editParams.getCompanyCode())
                    .appendPositionCode(editParams.getPositionCode()).appendEdit(loginUser);
            if (!sysUserPositionService.changePosition(userPositionBuilder.bulid())) {
                log.info("更新职位接口异常,参数:{}", JSON.toJSONString(userPositionBuilder.bulid()));
                throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
            }
        }

        UserBuilder userBuilder = new UserBuilder();
        userBuilder.append(editParams).appendEdit(loginUser);
        //编辑用户信息
        if (!sysUserService.edit(userBuilder.bulid(), loginUser)) {
            log.info("编辑用户接口异常,参数:{}", JSON.toJSONString(userBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return true;
    }

    public Boolean adminEditUser(AdminUserEditParams editParams, LoginUser loginUser) {
        //判断手机号码是否存在
        SysUser sysUser = sysUserService.queryUserByUserCode(editParams.getUserCode(), loginUser);
        new UserCheck(sysUser).checkNull("用户不存在");
        UserBuilder userBuilder = new UserBuilder();
        userBuilder.append(editParams).appendEdit(loginUser);
        //编辑用户信息
        if (!sysUserService.edit(userBuilder.bulid(), loginUser)) {
            log.info("编辑用户接口异常,参数:{}", JSON.toJSONString(userBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return true;
    }
}
